package com.hx.voice.recognition.auth.client.interceptor;

import com.hx.voice.recognition.auth.client.annotation.IgnoreClientToken;
import com.hx.voice.recognition.auth.client.config.ServiceAuthConfig;
import com.hx.voice.recognition.auth.client.jwt.ServiceAuthUtil;
import com.hx.voice.recognition.common.exception.auth.ClientForbiddenException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @descripe：应用授权拦截器 校验crm-admin 与crm-gate是否有资格调用其他应用
 * @company：南京华讯方舟通讯设备有限公司
 * @author：zhoujinbing
 * @time：2019/6/19 15:14
 * @version：V1.0
 */
@Slf4j
public class ServiceAuthRestInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private ServiceAuthUtil serviceAuthUtil;

    @Autowired
    private ServiceAuthConfig serviceAuthConfig;

    private List<String> allowedClient;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        //配置该注解，说明服务不进行拦截
        IgnoreClientToken annotation = handlerMethod.getBeanType().getAnnotation(IgnoreClientToken.class);
        if(annotation == null)
        {
            annotation = handlerMethod.getMethodAnnotation(IgnoreClientToken.class);
        }
        if(annotation != null)
        {
            //忽略放行，不进行验证
            return super.preHandle(request, response, handler);
        }

        String token = request.getHeader(serviceAuthConfig.getTokenHeader());
        String uniqueName = serviceAuthUtil.getInfoFormToken(token).getUniqueName();
        for (String client : serviceAuthUtil.getAllowedClient()) {
            //匹配，可以进行调用
            if(client.equals(uniqueName))
            {
                return super.preHandle(request,response,handler);
            }
        }

        throw new ClientForbiddenException("Client is Forbidden!");
    }


}